#include "gui.h"

#include <wx/wx.h>
#include <wx/statline.h>

enum
{
	wxID_BUTTON_START_CLICK = wxID_HIGHEST + 1,
	wxID_BUTTON_STOP_CLICK
};

BEGIN_EVENT_TABLE(VCServerFrame,wxFrame)
	EVT_CLOSE(VCServerFrame::OnClose)
	EVT_BUTTON(wxID_BUTTON_START_CLICK, VCServerFrame::OnClickButton)
	EVT_BUTTON(wxID_BUTTON_STOP_CLICK, VCServerFrame::OnClickButton)
END_EVENT_TABLE()

IMPLEMENT_CLASS(VCServerFrame, wxFrame)

VCServerFrame::VCServerFrame(const wxString& title)
: wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE & ~(wxRESIZE_BORDER | wxMAXIMIZE_BOX))
, m_staticTextPort(NULL)
, m_textCtrlPort(NULL)
, m_buttonStart(NULL)
, m_buttonStop(NULL)
, m_vcserver(NULL)
{
	wxPanel * panelTop = new wxPanel(this, wxID_ANY);

	m_staticTextPort = new wxStaticText(panelTop, wxID_STATIC, wxT("Server port:"));
	m_textCtrlPort = new wxTextCtrl(panelTop, wxID_ANY, wxT("6100"));
	m_buttonStart = new wxButton(panelTop, wxID_BUTTON_START_CLICK, wxT("Start"));
	m_buttonStop = new wxButton(panelTop, wxID_BUTTON_STOP_CLICK, wxT("Stop"));

	wxSizer * sizerTop = new wxBoxSizer(wxVERTICAL);
	wxSizer * sizerPort = new wxBoxSizer(wxHORIZONTAL);
	wxSizer * sizerButton = new wxBoxSizer(wxHORIZONTAL);

	sizerPort->Add(m_staticTextPort, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 5);
	sizerPort->Add(m_textCtrlPort, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);

	sizerButton->Add(m_buttonStart, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 5);
	sizerButton->Add(m_buttonStop, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);

	sizerTop->Add(sizerPort, 0, wxGROW | wxALL, 5);
	sizerTop->Add(sizerButton, 0, wxGROW | wxALL, 5);

	panelTop->SetSizer(sizerTop);
	sizerTop->Fit(this);
	sizerTop->SetSizeHints(this);

	m_buttonStop->Disable();

	m_vcserver = VCNewServer();
}

VCServerFrame::~VCServerFrame()
{
	if (m_vcserver)
	{
		VCDeleteServer(m_vcserver);
		m_vcserver = NULL;
	}
}

void VCServerFrame::OnClose(wxCloseEvent & evt)
{
	evt.Skip(true);
}

void VCServerFrame::OnClickButton(wxCommandEvent & evt)
{
	switch (evt.GetId())
	{
		case wxID_BUTTON_START_CLICK:
		{
			if (m_vcserver)
			{
				unsigned long port = 0;
				if (m_textCtrlPort->GetValue().ToULong(&port) && (port != 0))
				{
					if (m_vcserver->Start(NULL, (unsigned short)port))
					{
						m_buttonStop->Enable();
						m_buttonStart->Disable();
						m_textCtrlPort->Disable();
					}
				}
			}
		}
		break;
		case wxID_BUTTON_STOP_CLICK:
		{
			if (m_vcserver)
			{
				m_vcserver->Stop();
				m_buttonStop->Disable();
				m_buttonStart->Enable();
				m_textCtrlPort->Enable();
			}
		}
		break;
		default:
		{
		}
	}
}

